<?php
/**
 * A default authentication adapter for use with the authentication class.
 * 
 * @package Bedrock
 * @author Nick Williams
 * @version 1.0.0
 * @created 11/07/2008
 * @updated 11/07/2008
 */
class Bedrock_Common_Auth_Adapter extends Bedrock implements Bedrock_Common_Auth_Adapter_Interface {
	protected $_username = '';
	protected $_password = '';
	protected $_id = Bedrock_Common_Auth::RESULT_FAILED;
	protected $_failCount = 0;
	
	/**
	 * Initializes the authentication adapter object using the specified
	 * username and password.
	 *
	 * @param string $username the username to use
	 * @param string $password the password to use
	 */
	public function __construct($username, $password) {
		Bedrock_Common_Logger::logEntry();
		
		try {
			$this->_username = $username;
			$this->_password = $password;
			
			Bedrock_Common_Logger::logExit();
		}
		catch(Exception $ex) {
			Bedrock_Common_Logger::exception($ex);
			Bedrock_Common_Logger::logExit();
		}
	}
	
	/**
	 * Attempts to authenticate the specified user with the specified password.
	 * Returns the result of the authentication process (either the user's
	 * unique ID, or a failure code on failure).
	 *
	 * 
	 * @return mixed the result of the authentication process, on success the user's unique ID
	 */
	public function authenticate() {
		Bedrock_Common_Logger::logEntry();
		
		try {
			// Query Database
			$db = Bedrock_Common_Registry::get('database')->getConnection();
			$statement = $db->prepare('SELECT id, password FROM users WHERE username=:username');
			$statement->execute(array('username' => $this->_username));
			$res = $statement->fetchAll();
			
			if(count($res) == 0) {
				$this->_id = Bedrock_Common_Auth::RESULT_FAILED_USERNAME;
			}
			else {
				$res = $res[0];
				
				if($res['password'] != $this->_password) {
					$this->_id = Bedrock_Common_Auth::RESULT_FAILED_PASSWORD;
				}
				else {
					$this->_id = $res['id'];
				}
			}
			
			Bedrock_Common_Logger::logExit();
			return $this->_id;
		}
		catch(Exception $ex) {
			Bedrock_Common_Logger::exception($ex);
			Bedrock_Common_Logger::logExit();
		}
	}
	
	/**
	 * Stores the last failed authentication attempt for the current user.
	 */
	public function storeFailure() {
		Bedrock_Common_Logger::logEntry();
		
		try {
			$this->_failCount++;
			
			Bedrock_Common_Logger::logExit();
		}
		catch(Exception $ex) {
			Bedrock_Common_Logger::exception($ex);
			Bedrock_Common_Logger::logExit();
		}
	}
}
?>